package com.likerSai;

import com.likerSai.util.ListNode;

/**
 * 删除链表的倒数第N个节点
 * 虚拟的头结点是很巧妙的一步
 * @author sun.ye
 * @since 2022-03-24 17:46
 */
public class RemoveNthFromEnd {

    public static void main (String[] args) {
        ListNode head = new ListNode(1, new ListNode(2, new ListNode(3, new ListNode(4, new ListNode(5) ) ) ) );
//        ListNode head = new ListNode(1);
        head =  removeNthFromEnd(head,1);
        System.out.println(head.val);
        do{
            head = head.next;
            System.out.println(head.val);
        }while (head.next!=null);
    }


    public static ListNode removeNthFromEnd(ListNode head, int n){
        ListNode
                virtualHead = new ListNode(999,head),
                pre = virtualHead,
                last = virtualHead;
        int idxLast = 0;
        while (last.next!=null) {
            last = last.next;
            idxLast++;
            if (idxLast > n) {
                pre = pre.next;
            }
        }
        pre.next = pre.next.next;
        return virtualHead.next;
    }

}


